﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace GDoc.Utils
{
    public class CookiesUtil
    {
        public string this[string cookieName]
        {
            //TODO: Review this code, when you write a cookie and then you want to read it
            //this utility does not returns the modified cookie. Instead, it returns the old one
            //maybe using an intermidate collection to store modified cookies could solve this.
            get
            {
                var cookie = HttpContext.Current.Request.Cookies[cookieName];
                return (cookie != null) ? cookie.Value : null;
            }
            set
            {
                HttpContext.Current.Response.Cookies[cookieName].Value = value;
            }
        }

        public void Add(string cookieName, string value, int? expirationDays = null)
        {
            HttpCookie Cookie = new HttpCookie(cookieName, value);
            if (expirationDays.HasValue)
                Cookie.Expires = DateTime.Now.AddDays(expirationDays.Value);
            HttpContext.Current.Response.Cookies.Add(Cookie);
        }

        public void Delete(string cookieName)
        {
            HttpCookie Cookie = HttpContext.Current.Request.Cookies[cookieName];
            if (Cookie != null)
            {
                Cookie.Expires = DateTime.Now.AddDays(-2);
                HttpContext.Current.Response.Cookies.Add(Cookie);
            }
        }

        private CookiesUtil()
        {
        }

        [ThreadStatic]
        private static volatile CookiesUtil instance = null;

        /// <summary>
        /// Singleton instance for the current thread.
        /// </summary>
        public static CookiesUtil Current
        {
            get
            {
                if (instance == null)
                    instance = new CookiesUtil();
                return instance;
            }
            protected set
            {
                instance = value;
            }
        }
    }
}